import modem
import utime
from misc import Power
from usr.qframe import CurrentApp
from usr.qframe.logging import getLogger
from usr.qframe.ota import Fota, AppFota


logger = getLogger(__name__)


class ModuleUpgradeApi(object):

    @classmethod
    def upgrade(cls, version, url):
        try:
            # 应用脚本升级流程
            cls.update_app(version, url)
        except Exception as e:
            logger.error('upgrade failed, exception: {}'.format(e))

    @classmethod
    def update_app(cls, version, url):
        if version == CurrentApp().version:
            logger.warn('application already the latest version')
            return

        fota = AppFota()
        logger.info('app scripts tar file downloading')

        if not fota.download_tar(url):
            logger.error('app scripts tar file downloading error')
            return

        logger.info('app scripts tar file downloading success')

        fota.set_update_flag()
        logger.info('device restart for app updating after 5s')
        utime.sleep(5)
        Power.powerRestart()
